package com.kehongborui.fliggy.queue;

import com.kehongborui.fliggy.entity.Log;
import com.kehongborui.fliggy.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief 利用队列向数据库保存日志
 * @email 122162005@qq.com
 * @date 2018-09-10
 */
@Component
public class LogApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private LogsQueue logsQueue;
    @Autowired
    private LogMapper logMapper;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 判断是否是根容器的时间
        if (event.getApplicationContext().getParent() == null) {
            // 在这个地方实现我们的业务逻辑
            new Thread(() -> {
                while (true) {
                    Log log = logsQueue.pop();
                    logMapper.save(log);
                }
            }).start();
        }
    }
}
